/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package im.eventpackage;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Hashtable;

/**
 *
 * @author bluejack
 */
public class EventHandler {

    Hashtable events = null;

    public EventHandler() {
        events = new Hashtable();
    }
    
    public HashSet getRecipients(Event event) {
        return (HashSet) events.get(event);//(HashSet) Collections.synchronizedSet(new HashSet());
    }
    
    public void publish(Event event) {
        HashSet recipients = getRecipients(event);
        if(recipients==null) {
            recipients = new HashSet();//(HashSet) Collections.synchronizedSet(new HashSet());
        }
        events.put(event, recipients);
    }
    
    public void addRecipients(Event event, Collection newRecipients) {
        HashSet recipients = getRecipients(event);
        if(recipients!=null)
            recipients.addAll(newRecipients);
    }

    public void removeEvent(Event event) {
        events.remove(event);
    }
    public void removeRecipients(Event event, Collection newRecipients) {
        HashSet recipients = getRecipients(event);
        if(recipients!=null) {
            recipients.removeAll(newRecipients);
            if(recipients.isEmpty())
                events.remove(event);
        }
        else
            removeEvent(event);
    }

    public void removeRecipient(Event event, String recipient) {
        HashSet recipients = getRecipients(event);
        if(recipients!=null) {
            recipients.remove(recipient);
            if(recipients.isEmpty())
                events.remove(event);
        }
        else
            removeEvent(event);
    }
}
